import axios from "axios"
import { ElMessage } from "element-plus"
import router from "@/router/index.js"

const request = axios.create({
    baseURL: 'http://localhost:5000',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json'
    }
  })

// 请求拦截器
request.interceptors.request.use(
    config => {
      const user = JSON.parse(localStorage.getItem('code_user') || '{}')
      if (user.token) {
        config.headers.Authorization = `Bearer ${user.token}`
      }
      // 强制设置 Content-Type
      if (config.method.toLowerCase() === 'post' || config.method.toLowerCase() === 'put') {
        config.headers['Content-Type'] = 'application/json'
      }
      console.log('Request:', config.method, config.url, JSON.stringify(config.data))
      return config
    },
    error => {
      console.error('Request error:', error)
      return Promise.reject(error)
    }
  )

// 响应拦截器
request.interceptors.response.use(
    response => {
        let res = response.data
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            try {
                res = res ? JSON.parse(res) : {}
            } catch (e) {
                console.error('Response parse error:', res, e)
                res = {}
            }
        }
        // 记录响应数据以便调试
        console.debug('API response:', response.config.url, res)
        // 如果没有 status 字段，假设成功
        if (!res.status) {
            res.status = 'success'
        }
        return res
    },
    error => {
        console.error('API error:', error.response?.config?.url, error.response?.data)
        if (error.response?.status === 401) {
            const message = error.response?.data?.message || '登录状态失效'
            ElMessage.error(message)
            localStorage.removeItem('code_user')
            localStorage.removeItem('remember_user')
            setTimeout(() => {
                router.push('/login')
            }, 1000)
        } else if (error.response?.status === 404) {
            ElMessage.error(error.response?.data?.message || '未找到请求接口')
        } else if (error.response?.status === 500) {
            ElMessage.error(error.response?.data?.message || '系统异常，请查看后端控制台报错')
        } else {
            ElMessage.error(error.response?.data?.message || '请求失败')
        }
        return Promise.reject(error)
    }
)

export default request